package com.Shop.Center.controller;

import com.Shop.Center.entity.ItemOrder;
import com.Shop.Center.entity.ShoppingCartItem;
import com.Shop.Center.service.OrderService;
import com.Shop.Center.service.ShoppingCartService;
import org.springframework.stereotype.Controller;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;

@Controller
public class UserOrderController {
    @Resource
    private OrderService orderService;
    @Resource
    private ShoppingCartService shoppingCartService;

    @GetMapping("/orders/{userId}/{orderNo}")
    @ResponseBody
    public ItemOrder orderDetailPage(@PathVariable("orderNo") String orderNo, @PathVariable("userId")Long userId) {
        return orderService.getOrderDetailByOrderNo(orderNo, userId);
    }

    @GetMapping("/saveOrder/{userId}")
    @ResponseBody
    public String saveOrder(@PathVariable("userId")Long userId) {
        List<ShoppingCartItem> myShoppingCartItems = shoppingCartService.getMyShoppingCartItems(userId);
        if (CollectionUtils.isEmpty(myShoppingCartItems)) {
            //购物车中无数据则跳转至错误页
            return "购物车中无商品";
        }
        //保存订单并返回订单号
        String saveOrderResult = orderService.saveOrder(userId, myShoppingCartItems);
        //跳转到订单详情页
        return "redirect:/orders/" + saveOrderResult;
    }

    @PutMapping("/orders/{userId}/{orderNo}/cancel")
    @ResponseBody
    public String  cancelOrder(@PathVariable("orderNo") String orderNo, @PathVariable("userId") Long userId) {
        return orderService.cancelOrder(orderNo,userId);
    }

    @PutMapping("/orders/{userId}/{orderNo}/finish")
    @ResponseBody
    public String finishOrder(@PathVariable("orderNo") String orderNo, @PathVariable("userId") Long userId) {
        return orderService.finishOrder(orderNo,userId);
    }

    @GetMapping("/payPage/{userId}")
    @ResponseBody
    public String payOrder(@RequestParam("orderNo") String orderNo, @PathVariable("userId") Long userId) {
        ItemOrder itemOrder = orderService.getOrderDetailByOrderNo(orderNo,userId);
        //todo 判断订单userId
        //todo 判断订单状态
        return "mall/alipay";
    }

    @GetMapping("/paySuccess")
    @ResponseBody
    public String paySuccess(@RequestParam("orderNo") String orderNo, @RequestParam("payType") int payType,
                             @RequestParam("userId") Long userId) {
        Double credit = orderService.paySuccess(orderNo, payType,userId);
        if (credit<0) {
            return "订单不存在";
        } else {
            return "支付成功！获得"+credit+"点积分！";
        }
    }
}
